<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>goods-details</title><!--商品详情页-->
    <link href="/css/goods.css" rel="stylesheet">
    <link href="/css/message.css" rel="stylesheet"/>
    <script src="/js/alert.js" type="text/javascript"></script>
    <script src="/js/jquery-3.4.1.js" type="text/javascript"></script>
    <script th:inline="javascript" type="text/javascript">
        $(function () {
            // 09月01日  22:00  秒杀价￥8.9
            let spikeTime = [[${spu.spikeTime}]];

            function add0(num) {
                // 个位数的值在前面补0
                return num < 10 ? '0' + num : num
            }
            const date = new Date(spikeTime)
            // const Y = date.getFullYear()
            const M = date.getMonth() + 1
            const D = date.getDate()
            const h = date.getHours()
            const m = date.getMinutes()
            // const s = date.getSeconds()
            spikeTime = add0(M) + '月' + add0(D) + '日&nbsp;&nbsp;' + add0(h) + ':' + add0(m);
            let price = [[${sku.priceSpike}]];
            $(".greyFont").html(spikeTime)
            $(".spike").html(price)

            // 倒计时 获取元素
            let hour = document.querySelector(".hour");
            let minute = document.querySelector(".minute");
            let second = document.querySelector(".second");
            // 我们先调用countDown函数，可以避免在打开界面后停一秒后才开始倒计时
            countDown();
            // 定时器 每隔一秒变化一次
            setInterval(countDown, 1000);

            function countDown() {
                //获取当前时间的时间戳（单位毫秒）
                let nowTime = new Date();
                // 截止时间的时间戳（单位毫秒）date
                // 把剩余时间毫秒数转化为秒
                let times = (date - nowTime) / 1000;
                if (times > 0) {
                    //计算小时数 转化为整数
                    let h = parseInt(times / 60 / 60);
                    //如果小时数小于 10，要变成 0 + 数字的形式 赋值给盒子
                    hour.innerHTML = h < 10 ? "0" + h : h;
                    //计算分钟数 转化为整数
                    let m = parseInt(times / 60 % 60);
                    //如果分钟数小于 10，要变成 0 + 数字的形式 赋值给盒子
                    minute.innerHTML = m < 10 ? "0" + m : m;
                    //计算描述 转化为整数
                    let s = parseInt(times % 60);
                    //如果秒钟数小于 10，要变成 0 + 数字的形式 赋值给盒子
                    second.innerHTML = s < 10 ? "0" + s : s;
                } else {
                    // 可以抢购
                    $(".goBuy").css({"background": "#01c30b"})
                    $(".remainTime").css({"display": "none"})
                }
            }

            // 选择颜色
            $(".ifCheck").click(function () {
                $(".ifCheck").css({"border": "1px solid #ccc"}); // 设置所有div无背景色
                $(this).css({"border": "1px solid #e4393c"});    // 设置当前点击div背景色为红色，色号#e4393c
                // 获取当前选中颜色
                const colorNow = $(this).attr("name");
                console.log(colorNow);
                let spuId = [[${spu.id}]];
                console.log(spuId)
                // 通过点击向后台传颜色来换页面图片
                $.ajax({
                    url: "/goods/transformGood",
                    type: "POST",
                    data: {
                        "spuId": spuId,
                        "color": colorNow
                    },
                    success: function (data) {
                        let good = data.data;
                        let img = "<img class=\"img-fluid\"  src=" + good.img + ">";
                        $(".sku-img").html(img)
                        $(".sku-color").html(good.color)
                        $(".spike").html(good.priceSpike)
                        $(".priceSku").html(good.price)
                        $(".stock").html(good.stock)
                        $(".sku-img").attr("name", good.id)
                    }
                })
            });

            // 数量加减
            $("body").on("click", ".num-jian", function (m) {
                let obj = $(this).closest("ul").find(".input-num");
                if (obj.val() <= 1) {
                    obj.val(1);
                } else {
                    obj.val(parseInt(obj.val()) - 1);
                }
                obj.change();
            });
            $("body").on("click", ".num-jia", function (m) {
                let obj = $(this).closest("ul").find(".input-num");
                // obj.val(parseInt(obj.val()) + 1);
                obj.val(1);
                obj.change();
            });
        });

        function goOrder() {
            if ($(".remainTime").css('display') === 'none') {
                let data = {
                    "user": {
                        "id": [[${user.id}]],
                        "username": [[${user.username}]],
                        "password": [[${user.password}]],
                        "alias": [[${user.alias}]],
                        "gmtCreate": [[${user.gmtCreate}]],
                        "gmtModified": [[${user.gmtModified}]]
                    },
                    "spu": {
                        "id": parseInt($(".sku-img").attr("name")),
                        "goodName": [[${spu.id}]]
                    },
                    "sku": {
                        "id": parseInt($(".sku-img").attr("name")),
                        "spuId": [[${spu.id}]],
                        "img": $(".sku-img").attr("src"),
                        "price": $(".priceSku").text(),
                        "priceSpike": $(".spike").text(),
                        "color": $(".sku-color").text(),
                        "stock": $(".stock").text()
                    }
                };
                // 将data对象转换为JSON字符串
                let jsonData = JSON.stringify(data);
                // 通过点击向后台传用户和商品数据进行抢购
                // 限流 同一个用户5s/3次，超过就拒绝，
                // let date = new Date();
                // if (date + 3 > new Date()) {
                //
                // }
                $.ajax({
                    url: "/secKill/secKillGoods",
                    type: "POST",
                    data: jsonData,
                    contentType: "application/json",
                    dataType: 'json',
                    success: function (data) {
                        if (data.code === 200 || data.code === 600) {
                            getResult();
                        } else {
                            commonUtil.message(data.message, 'warning')
                        }
                    }
                })
            }
        }

        function getResult() {
            $.ajax({
                url: "/secKill/getResult",
                type: "GET",
                data: {
                    "userId": [[${user.id}]],
                    "skuId": $(".sku-img").attr("name")
                },
                success: function (data) {
                    if (data === 1) {
                        commonUtil.message("已秒杀成功", 'success')
                    } else {
                        commonUtil.message("正在排队中", 'primary')
                    }
                }
            })
        }
    </script>
</head>
<body>
    <div class="container">
        <!-- Content here -->
        <div class="conPlus">
            <div class="sku-img" th:name="${sku.id}">
                <img th:src="${sku.img}" class="img-fluid" alt=""/>
            </div>
            <div class="item-right">
                <div class="sku-name">
                    [[${spu.goodName}]]
                    <span class="sku-color">[[${sku.color}]]</span>
                </div>
                <div class="item-seckill">
                    <i class="seckill-yg"></i>
                    <strong class="redFont">秒杀预告</strong>
                    <span class="greyFont">9月1日 22:00&nbsp;&nbsp;</span>
                    <strong class="priceSpike">&nbsp;&nbsp;秒杀价￥</strong>
                    <strong class="priceSpike spike">33.9</strong>
                    <div class="remainTime">
                        距离开始还剩
                        <span class="hour">12</span> <strong>:</strong>
                        <span class="minute">20</span> <strong>:</strong>
                        <span class="second">30</span>
                    </div>
                </div>
                <div class="normal">
                    <div class="priceText">商品价格</div>
                    <span class="price">￥</span>
                    <span class="price priceSku">[[${sku.price}]]</span>
                </div>
                <div style="display: inline-flex;margin-top: 10px">
                    <span class="priceText">配 送 至</span>
                    <div class="address">
                        <select aria-label="请选择配送地址">
                            <option selected>请选择配送地址</option>
                            <option value="1">湖北省武汉市洪山区珞瑜路狮城名居</option>
                            <option value="2">陕西省西安市雁塔区丈八街道南窑头社区东区</option>
                            <option value="3">山西省太原市小店区肉联厂西</option>
                        </select>
                    </div>
                    <div class="priceText">
                        剩余库存：<span class="stock">[[${sku.stock}]]</span>
                    </div>
                </div>
                <div class="line"></div>
                <div class="colorRow">
                    <span class="typeText">选择颜色</span>
                    <div class="deChoice">
                        <div th:each="col,colStat:${color}">
                            <div class="ifCheck" th:name="${col}"
                                 th:if="${col.contains(sku.color)}"
                                 style="border:1px solid #e4393c">
                                [[${col}]]
                            </div>
                            <div class="ifCheck" th:name="${col}"
                                 th:if="${!col.contains(sku.color)}">
                                [[${col}]]
                            </div>
                        </div>
                    </div>
                </div>
                <div class="line"></div>
                <div class="addCount">
                    <ul class="btn-numbox">
                        <li><span class="quantity">数量</span></li>
                        <li>
                            <ul class="count">
                                <li><span id="num-jian" class="num-jian">-</span></li>
                                <li><input type="text" class="input-num" id="input-num" value="1"/></li>
                                <li><span id="num-jia" class="num-jia">+</span></li>
                            </ul>
                        </li>
                        <li class="chLibrary">
                            <span class="library">有货</span>
                        </li>
                    </ul>
                    <!--<div class="car" id="car">-->
                    <!--    加入购物车-->
                    <!--</div>-->
                    <div class="goBuy" onclick="goOrder()">
                        立即抢购
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
